const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const redisService = require('./services/redisService');

// 加载环境变量
dotenv.config();

// 初始化Redis连接（可选）
setTimeout(() => {
  redisService.init().catch(err => {
    console.warn('Redis初始化失败:', err.message);
    console.log('应用将继续运行，但Redis相关功能将不可用');
  });
}, 1000);

// 创建Express应用
const app = express();

// 中间件
app.use(helmet()); // 安全HTTP头
app.use(cors()); // 跨域资源共享
app.use(express.json()); // 解析JSON请求体
app.use(express.urlencoded({ extended: true })); // 解析URL编码的请求体

// 导入路由
const userRoutes = require('./routes/userRoutes');
const projectRoutes = require('./routes/projectRoutes');
const aiAssistantRoutes = require('./routes/aiAssistantRoutes');
const challengeRoutes = require('./routes/challengeRoutes');
const codeExecutionRoutes = require('./routes/codeExecutionRoutes');
const redisTestRoutes = require('./routes/redisTestRoutes');

// 使用路由
app.use('/api/users', userRoutes);
app.use('/api/projects', projectRoutes);
app.use('/api/ai-assistant', aiAssistantRoutes);
app.use('/api/challenges', challengeRoutes);
app.use('/api/execute', codeExecutionRoutes);
app.use('/api/redis-test', redisTestRoutes);

// 根路由
app.get('/', (req, res) => {
  res.json({ message: '少儿图形化编程在线交互网站API服务' });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

module.exports = app;